package com.fhzn.auth.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fhzn.auth.entity.UserDataResource;
import org.apache.ibatis.annotations.Insert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 老顾
 * @apiNote
 * @since 2024/1/18
 */
public interface UserDataResourceMapper extends BaseMapper<UserDataResource> {

    /**
     * 根据数据资源id获取用户昵称
     *
     * @param dataResourceIds 数据资源id
     * @return 用户昵称列表
     */
    default List<String> getUsersByDataResource(List<Integer> dataResourceIds) {
        LambdaQueryWrapper<UserDataResource> wrapper = Wrappers.lambdaQuery();
        wrapper.in(UserDataResource::getDataResId, dataResourceIds);
        return selectList(wrapper).stream().map(UserDataResource::getNickname).collect(Collectors.toList());
    }

    /**
     * 根据用户昵称获取数据资源id
     *
     * @param handler 用户昵称
     * @return 数据资源id列表
     */
    default List<Integer> getUsersByNickname(String handler) {
        LambdaQueryWrapper<UserDataResource> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserDataResource::getNickname, handler);
        wrapper.orderByAsc(UserDataResource::getSort);
        return selectList(wrapper).stream().map(UserDataResource::getDataResId).collect(Collectors.toList());
    }

    /**
     * 根据数据资源id删除用户数据权限
     *
     * @param id 数据资源id
     */
    default void deleteByDataResourceId(Integer id) {
        LambdaQueryWrapper<UserDataResource> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserDataResource::getDataResId, id);
        delete(wrapper);
    }

    /**
     * 批量插入用户权限
     *
     * @param userDataResList 用户数据资源列表
     * @return true
     */
    @Insert("<script>" +
            "INSERT INTO abstract_auth_user_dataresource (nickname, data_res_id, sort, creator, modifier) VALUES " +
            "<foreach collection='userDataResList' item='item' separator=','>" +
            "(#{item.nickname}, #{item.dataResId}, #{item.sort}, #{item.creator}, #{item.modifier})" +
            "</foreach>" +
            "</script>")
    boolean saveBatch(List<UserDataResource> userDataResList);
}
